package chaowan.Controller;

import chaowan.Service.OrderMainService;
import chaowan.Service.ShopUserService;
import chaowan.pojo.OrderMain;
import chaowan.pojo.ShopUser;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderMainController {

    @Resource
    private OrderMainService orderMainService;
    @Resource
    private ShopUserService shopUserService;

    @GetMapping("/list")
    public String list(Model model) {
        List<OrderMain> orders = orderMainService.getAllOrders();
        model.addAttribute("orderList", orders);
        return "ordermain/list";
    }

    @GetMapping("/addForm")
    public String addForm(Model model) {
        model.addAttribute("order", new OrderMain());
        model.addAttribute("userList", shopUserService.getAllUsers());
        return "ordermain/add";
    }

    @PostMapping("/add")
    public String add(OrderMain orderMain) {
        orderMainService.save(orderMain);
        return "redirect:/order/list";
    }

    @GetMapping("/editForm/{oid}")
    public String editForm(@PathVariable Long oid, Model model) {
        OrderMain order = orderMainService.getOrderById(oid);
        model.addAttribute("order", order);
        model.addAttribute("userList", shopUserService.getAllUsers());
        return "ordermain/edit";
    }

    @PostMapping("/update")
    public String update(OrderMain orderMain) {
        orderMainService.update(orderMain);
        return "redirect:/order/list";
    }

    @GetMapping("/delete/{oid}")
    public String delete(@PathVariable Long oid, RedirectAttributes redirectAttributes) {
        try {
            int result = orderMainService.deleteById(oid);
            if (result > 0) {
                redirectAttributes.addFlashAttribute("message", "订单删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("error", "无法删除该订单，订单状态不允许删除！");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败，请稍后再试！");
        }
        return "redirect:/order/list";
    }

    @GetMapping("/myOrders")
    public String myOrders(Model model, HttpSession session) {
        Object userObj = session.getAttribute("loginUser");
        if (userObj == null) {
            return "redirect:/user/login";
        }
        ShopUser user = (ShopUser) userObj;
        List<OrderMain> orders = orderMainService.getOrdersByUserId(user.getUid());
        model.addAttribute("orderList", orders);
        return "order_list";
    }
}